package com.example.redisdistribute.common;

import com.example.redisdistribute.service.IRedisDistributedLock;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * RedisLockAop
 *
 * @ClassName RedisLockAop
 * @Author lixingxing
 * @Date 2021/08/11 下午 15:29
 * @Version 1.0
 */
@Component
@Slf4j
@Aspect
public class RedisLockAop {

    @Autowired
    private IRedisDistributedLock redisDistributedLock;

    @SuppressWarnings("ArgNamesErrorsInspection")
    @Around(value = "@annotation(distributedLock)")
    public Object doAroundAdvice (ProceedingJoinPoint proceedingJoinPoint
            , DistributedLock distributedLock) {
        String key = getKey(proceedingJoinPoint, distributedLock);
        Boolean success = redisDistributedLock.lock(
                key,
                distributedLock.timeOut(),
                distributedLock.expire(),
                distributedLock.retryTimes()
        );
        try {
            if (success) {
                log.info(Thread.currentThread().getName() + " 加锁成功");
                return proceedingJoinPoint.proceed();
            }
            log.info(Thread.currentThread().getName() + "加锁失败");
            return null;
        } catch (Throwable throwable) {
            throwable.printStackTrace();
            return null;
        } finally {
            if (success) {
                boolean result = redisDistributedLock.unLock(key);
                log.info(Thread.currentThread().getName() + " 释放锁结果：{}", result==true?"成功":"失败");
            }
        }
    }

    private String getKey(JoinPoint joinPoint, DistributedLock lock) {
        if (!StringUtils.isBlank(lock.key())) {
            return lock.key();
        }
        return joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
    }

}
